<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Simple login controller 
 */
class Login extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('form');
    }

    function index() {
        // load view
        $data['title'] = 'Bejelentkezés';
        $this->load->view('admin/login_view', $data);
    }

    function validate_login() {
        //This method will have the credentials validation
        $this->load->library('form_validation');

        $this->form_validation->set_rules('username', 'Felhasználónév', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', 'Jelszó', 'trim|required|xss_clean|callback_check_database');
  
        if ($this->form_validation->run() == FALSE) {
            //Field validation failed.  User redirected to login page
            $data['auth_error'] = 1;
            // load view
            $data['title'] = 'Bejelentkezés';
            $this->load->view('admin/login_view', $data);
        } else {
            //Go to private area
            redirect('admin/main');
        }
    }

    /**
     * Callback function for form_validation
     * @param type $password
     * @return type 
     */
    function check_database($password) {
        //Field validation succeeded.  Validate against database
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        
        try {
            //query the database
            $this->zen_auth->login($username, $password);
        } catch (Exception $e) {
            return false;
        }
        // session set&done
        return true;
    }

}
